//
//  GRLocationViewController.m
//  YC_GRice
//
//  Created by Feng Liu on 2018/8/27.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRLocationViewController.h"
#import "GRCurrentCityHeader.h"
#import "GRLocationPoisViewCell.h"
#import "GRHotCityHeaderView.h"

@interface GRLocationViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, GRBasisProtocol>
{
    BOOL             isSelectCity;
    NSArray        *letterKeys;
    NSDictionary  *cityDictionary;
}
// Layout
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;

@property (weak, nonatomic) IBOutlet UILabel *cityName;
@property (weak, nonatomic) IBOutlet UIImageView *arrowIcon;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *cityBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) GRCurrentCityHeader *cityHeader;
@property (nonatomic, strong) NSArray *poisList;
@property (nonatomic, strong) NSArray *aroundPois;

@end

@implementation GRLocationViewController

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [GRLocationManager defaultManager].completionHandler = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (IS_IPHONEX) {
        _topLayout.constant = 88;
    }
    self.navigationItem.title = @"定位";
    // Do any additional setup after loading the view from its nib.
    GRLocationManager *locationManager = [GRLocationManager defaultManager];
    self.cityName.text        = locationManager.city;
    _cityHeader                = [[GRCurrentCityHeader alloc] initWithFrame:CGRectMake(0, 0, KscreenWidth, 48)];
    _cityHeader.delegate               = self;
    self.cityHeader.currentCity.text = [locationManager.currentpoi.city stringByReplacingOccurrencesOfString:@"市" withString:@""];
    self.tableView.tableHeaderView  = self.cityHeader;
    self.tableView.tableFooterView   = [UIView new];
    self.tableView.sectionIndexColor = HEXCOLOR(0x395B7E);
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[GRLocationPoisViewCell class] forCellReuseIdentifier:@"GRLocationPoisViewCell"];
    [self.tableView registerClass:[GRHotCityHeaderView class] forHeaderFooterViewReuseIdentifier:@"GRHotCityHeaderView"];
    
    letterKeys      = locationManager.letterKeys;
    cityDictionary = locationManager.cityDictionary;
    
    [locationManager poiAroundSearch:locationManager.currentLocation];
    WEAKSELF
    locationManager.completionHandler = ^(NSArray<AMapPOI *> *pois, BOOL aroundRequest) {
        if (aroundRequest) {
            weakSelf.aroundPois = pois;
        }
        weakSelf.poisList         = pois;
        [weakSelf.tableView reloadData];
    };
}

- (IBAction)didSelectCityAction:(UIButton *)sender {
    sender.selected       = !sender.selected;
    isSelectCity            = sender.selected;
    NSString *imgName  = !sender.selected ? @"Home_07" : @"Home_08";
    self.arrowIcon.image = [UIImage imageNamed:imgName];
    self.cityHeader.isLocation = !sender.selected;
    [self.tableView reloadData];
}


- (IBAction)textFieldDidChange:(UITextField *)sender {
    if (sender.text.length == 0) {
        self.poisList = self.aroundPois;
        [self.tableView reloadData];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [[GRLocationManager defaultManager] poiKeyWord:textField.text city:self.cityName.text];
    [textField resignFirstResponder];
    return YES;
}

#pragma MARK --------  <UITableViewDelegate, UITableViewDataSource>  -----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return isSelectCity ? letterKeys.count : 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isSelectCity) {
        return [cityDictionary[letterKeys[section]] count];
    }
    return self.poisList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isSelectCity) {
        UITableViewCell *cell       = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        NSArray *citys              = cityDictionary[letterKeys[indexPath.section]];
        cell.textLabel.text           = citys[indexPath.row];
        return cell;
    }else {
        GRLocationPoisViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GRLocationPoisViewCell" forIndexPath:indexPath];
        AMapPOI *poi               = self.poisList[indexPath.row];
        cell.textLabel.text         = poi.name;
        cell.detailTextLabel.text = poi.address;
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    GRHotCityHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"GRHotCityHeaderView"];
    if (isSelectCity) {
        header.titleLabel.text = letterKeys[section];
    }else {
        header.titleLabel.text = @"附近地址";
    }
    return header;
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return isSelectCity ? letterKeys : nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isSelectCity) {
        NSArray *citys     = cityDictionary[letterKeys[indexPath.section]];
        self.cityName.text = citys[indexPath.row];
        [self didSelectCityAction:self.cityBtn];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }else {
        GRLocationManager *locationManager = [GRLocationManager defaultManager];
        AMapPOI *poi                    = self.poisList[indexPath.row];
        locationManager.city          = [poi.city stringByReplacingOccurrencesOfString:@"市" withString:@""];
        locationManager.adcode      = poi.adcode;
        locationManager.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);

        [[NSNotificationCenter defaultCenter] postNotificationName:GRDidFinishLocationNotification object:self userInfo:@{LocationKey : poi, DragMapKey : @(YES)}];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)backUpViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
